import re
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.mixins import CreateModelMixin
from rest_framework.decorators import action
from django.core.cache import cache
from django.conf import settings

from . import serializer
from utils.response import APIResponse
from . import models
from libs.t_sms import get_code, send_code
from .throttles import SMSRateThrottle


class LoginView(ViewSet):
    @action(methods=['post'], detail=False)
    def login(self, request, *args, **kwargs):
        ser = serializer.LoginSerializer(data=request.data, context={'request': request})
        if ser.is_valid():
            token = ser.context['token']
            user = ser.context['user']
            icon = ser.context['icon']
            return APIResponse(token=token, username=user.username, icon=icon)
        else:
            return APIResponse(status=1, msg='用户名或密码错误')

    @action(methods=['get'], detail=False)
    def check_mobile(self, request, *args, **kwargs):
        mobile = request.GET.get('mobile')
        import re
        if re.match(r'^1[3-9][0-9]{9}$', mobile):
            user = models.User.objects.filter(mobile=mobile).first()
            if user:
                return APIResponse(msg='手机号已存在')
            else:
                return APIResponse(status=1, msg='手机号未注册')
        else:
            return APIResponse(status=2, msg='手机号不合法')


class SendCodeView(ViewSet):
    throttle_classes = [SMSRateThrottle, ]

    @action(methods=['get', ], detail=False)
    def send_code(self, request, *args, **kwargs):
        mobile = request.query_params.get('mobile')
        # 1验证手机号
        if re.match(r'^1[3-9][0-9]{9}$', mobile):
            # 2生成验证码
            code = get_code()
            # 3发送验证码
            res, sms_msg = send_code(mobile, code)
            if res:
                # 4发送成功，保存验证码(保存到缓存)
                cache.set(settings.SMS_CACHE_KEY % {'mobile': mobile}, code, settings.SMS_CACHE_TIME)
                return APIResponse(msg=sms_msg)
            else:
                return APIResponse(status=1, msg=sms_msg)
        else:
            return APIResponse(status=2, msg='手机号不合法')

    @action(methods=['post', ], detail=False)
    def code_login(self, request, *args, **kwargs):
        ser = serializer.LoginCodeSerializer(data=request.data, context={'request': request})
        if ser.is_valid():
            token = ser.context['token']
            user = ser.context['user']
            icon = ser.context['icon']
            return APIResponse(token=token, username=user.username, icon=icon)
        else:
            return APIResponse(status=1, msg=ser.errors)


class CodeRegisterView(GenericViewSet, CreateModelMixin):
    queryset = models.User.objects.all()
    serializer_class = serializer.CodeRegisterSerializer

    def create(self, request, *args, **kwargs):
        res = super().create(request, *args, **kwargs)
        return APIResponse(msg='注册成功', username=res.data.get('username'))
